package com.yukh.framework.spring.ext;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.util.PropertyPlaceholderHelper;

/**
 * 
 * @author kunhua.yu
 */
public class PropertyPlaceholderConfigurer extends 
	org.springframework.beans.factory.config.PropertyPlaceholderConfigurer{
	/**
	 * root property file location
	 */
	private Resource rootLocation;
	
	/**
	 * child property file locations
	 */
	private String[] childLocations;
	
	/**
	 * community properties
	 */
	private Properties properties;
	
	private Resource getResource(String location){
		PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper(
				DEFAULT_PLACEHOLDER_PREFIX, DEFAULT_PLACEHOLDER_SUFFIX);
		location = helper.replacePlaceholders(location, properties);
		// spring 2.5
		// location = parseStringValue(location, properties, new HashSet());
		DefaultResourceLoader loader = new DefaultResourceLoader();
		return loader.getResource(location);
	}
	
	public Resource getRootLocation() {
		return rootLocation;
	}
	
	public void setRootLocation(Resource rootLocation)throws IOException {
		this.rootLocation = rootLocation;
		properties = new Properties();
		InputStream in = rootLocation.getInputStream();
		try {
			properties.load(in);
		} finally{
			in.close();
		}
	}

	public String[] getChildLocations() {
		return childLocations;
	}

	public void setChildLocations(String[] childLocations) {
		this.childLocations = childLocations;
		Resource[] resources = new Resource[childLocations.length + 1];
		for (int i = 0, n = childLocations.length; i < n; i++) {
			resources[i] = getResource(childLocations[i]);
		}
		resources[childLocations.length] = rootLocation;
		setLocations(resources);
	}
}
